<template>
  <div class="data-statistics">
    <ContentForm name="缺陷多维度统计">
      <div slot="searchform" class="form-top">
        <form action="">
          <p class="form-top-p">
            <el-select v-model="valuek.deptCode" clearable placeholder="选择供电段" @change="line">
              <el-option
                v-for="item in formz.selectSection"
                :key="item.value"
                :label="item.deptName"
                :value="item.deptCode" />
            </el-select>
          </p>
          <p class="form-top-p">
            <el-select v-model="valuek.lineCode" clearable placeholder="选择线路">
              <el-option
                v-for="item in formz.selectLin"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </p>
          <p class="form-top-p">
            <el-select v-model="valuek.cType" multiple collapse-tags clearable placeholder="装置类型">
              <el-option
                v-for="item in formz.deviceType"
                :key="item.cType"
                :label="item.cType"
                :value="item.cType" />
            </el-select>
          </p>
          <p class="form-top-p">
            <el-select v-model="valuek.defectStatus" clearable placeholder="选择状态">
              <el-option
                v-for="item in formz.defectStatus"
                :key="item.code"
                :label="item.label"
                :value="item.code" />
            </el-select>
          </p>
          <p class="form-top-p">
            <el-date-picker
              v-model="valuek.selectShij"
              class="input-long"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM" />
          </p>
          <p class="form-top-p">
            <el-button type="primary" size="mini" icon="el-icon-search" @click="getlist">查询</el-button>
          </p>
        </form>
      </div>
      <div slot="valueform" ref="valueform" v-loading="loading" class="value-form" style="padding-top:4px;">
        <div class="radioList">
          <div class="radioItem">
            <span>主维度：</span>
            <el-radio-group v-model="valuek.mainDimensionsType">
              <el-radio label="线路">线路</el-radio>
              <el-radio label="段">段</el-radio>
            </el-radio-group>
          </div>
          <div class="radioItemR">
            <span>次维度：</span>
            <el-radio-group v-model="valuek.timeDimensionsType">
              <el-radio label="级别">级别</el-radio>
              <el-radio label="装置类型">装置类型</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div id="linebar-chart" style="height:calc(100% - 32px);width:100%;" />
      </div>
    </ContentForm>
  </div>
</template>

<script>
import { findDefectMultipleDimensions, getDeviceType } from '@/api/cms/data-statistics'
import { line, getListSection } from '@/api/cms/detect-data/basic'
import echarts from 'echarts'
export default {
  name: 'Defectdimension',
  components: {
  },
  data() {
    return {
      myChart: null,
      loading: false,
      alldata: {},
      valuek: {
        cType: [], // 装置类型
        defectStatus: '', // 缺陷状态
        mainDimensionsType: '线路', // 主维度
        timeDimensionsType: '级别', // 次维度
        deptCode: '',
        selectShij: [],
        lineCode: '' // 选择线路
      },
      formz: {
        selectSection: [], // 所选得供电段
        selectLin: [],
        deviceType: [], // 装置类型
        defectStatus: [{ label: '未处理', code: '0' }, { label: '已审核', code: '1' },
          { label: '下发', code: '2' }, { label: '已整改', code: '3' }, { label: '已销号', code: '4' }
        ]
      }
    }
  },
  watch: {
    'valuek.mainDimensionsType': function() {
      this.getlist()
    },
    'valuek.timeDimensionsType': function() {
      this.getlist()
    }
  },
  mounted() {
    // 获取当前年月,选择默认时间段 12个月
    const year = new Date().getFullYear()
    const month = new Date().getMonth()
    const startdata = (Number(month) + 2) > 12 ? (Number(year) - 1) + '-01' : (Number(month) + 2) < 10 ? (Number(year) - 1) + `-0${(Number(month) + 2)}` : (Number(year) - 1) + `-${(Number(month) + 2)}`
    const enddata = (Number(month) + 1) < 10 ? year + `-0${(Number(month) + 1)}` : year + `-${(Number(month) + 1)}`
    this.valuek.selectShij = [startdata, enddata]
    getListSection().then(res => {
      const selectSection = []
      if (res.data) {
        res.data.forEach(item => {
          const section = {}
          section.deptCode = item.deptCode + '-' + item.deptName + '-' + item.id
          section.deptName = item.deptName
          selectSection.push(section)
        })
      }
      this.formz.selectSection = selectSection
    })
    getDeviceType().then(res => {
      this.formz.deviceType = res.data
    })
    this.line()
    this.getlist()
    // 监听屏幕变化，改变echarts尺寸
    const _this = this
    window.addEventListener('resize', function() {
      _this.$nextTick(_ => {
        _this.myChart.resize()
      })
    })
  },
  methods: {
    line(val) {
      var obj = {
        deptId: ''
      }
      if (val) {
        obj.deptId = val.split('-')[2]
      }
      line(obj).then(response => {
        // console.log('线路下拉框', response)
        const lines = []
        if (response.data) {
          response.data.forEach(item => {
            const line = {}
            line.value = item.lineCode + '-' + item.lineName
            line.label = item.lineName
            lines.push(line)
          })
        }
        this.formz.selectLin = lines
      })
    },
    getlist() {
      if (!this.valuek.selectShij || !this.valuek.selectShij[0]) {
        this.$alert('请选择时间', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      var cType = ''
      for (const item of this.valuek.cType) {
        cType = cType + item + ','
      }
      cType = cType.substring(0, cType.length - 1)
      var obj = Object.assign({}, this.valuek, {
        selectShij: '',
        startTime: this.valuek.selectShij[0],
        endTime: this.valuek.selectShij[1],
        cType: cType,
        lineCode: this.valuek.lineCode.split('-')[0],
        deptCode: this.valuek.deptCode.split('-')[0]
      })
      this.alldata = {}
      this.loading = true
      findDefectMultipleDimensions(obj).then(res => {
        this.loading = false
        if (res.data.data.length) {
          this.alldata = res.data.data
          this.handleData()
        } else {
          var echartsData = {
            title: '暂无数据',
            legend: [],
            xAxisData: [],
            series: []
          }
          this.getecharts(echartsData)
        }
      })
    },
    handleData() {
      var echartsData = {
        title: '',
        legend: [],
        xAxisData: [],
        series: []
      }
      var that = this
      this.alldata = this.alldata.map(function(item) {
        if (that.valuek.timeDimensionsType === '级别') {
          if (!echartsData.xAxisData.includes(item.userGradeName)) { echartsData.xAxisData.push(item.userGradeName) }
        } else if (that.valuek.timeDimensionsType === '装置类型') {
          if (!echartsData.xAxisData.includes(item.cType)) { echartsData.xAxisData.push(item.cType) }
        }
        if (that.valuek.mainDimensionsType === '线路') {
          if (!echartsData.legend.includes(item.lineName)) { echartsData.legend.push(item.lineName) }
        } else if (that.valuek.mainDimensionsType === '段') {
          if (!echartsData.legend.includes(item.deptName)) { echartsData.legend.push(item.deptName) }
        }

        return item
      })
      echartsData.legend.forEach((item) => {
        const obj = {
          name: item,
          type: 'bar',
          barMaxWidth: 100,
          data: new Array(echartsData.xAxisData.length).fill(0)
        }
        this.alldata.forEach(child => {
          if (child.lineName === item || child.deptName === item) {
            if (that.valuek.timeDimensionsType === '级别') {
              obj.data[echartsData.xAxisData.indexOf(child.userGradeName)] = child.count
            } else if (that.valuek.timeDimensionsType === '装置类型') {
              obj.data[echartsData.xAxisData.indexOf(child.cType)] = child.count
            }
          }
        })
        echartsData.series.push(obj)
      })
      echartsData.title = '缺陷多维度统计图'
      if (this.valuek.lineCode && this.valuek.lineCode.split('-')[1]) {
        echartsData.title = this.valuek.lineCode.split('-')[1] + '-' + echartsData.title
      }
      if (this.valuek.deptCode && this.valuek.deptCode.split('-')[1]) {
        echartsData.title = this.valuek.deptCode.split('-')[1] + '-' + echartsData.title
      }
      this.getecharts(echartsData)
    },
    getecharts(echartsData) {
      const chart = echarts.init(document.getElementById('linebar-chart'), 'light')
      this.myChart = chart
      var option = {
        // color: ['#409EFF', '#cccccc'],
        title: {
          text: echartsData.title,
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: echartsData.legend,
          bottom: 0
        },
        grid: {
          left: '40',
          right: '40',
          bottom: '40',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            axisLabel: {
              interval: 0, // 坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
              rotate: 38 // 调整数值改变倾斜的幅度（范围-90到90）
            },
            data: echartsData.xAxisData,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            name: '条'
          }
        ],
        series: echartsData.series
      }
      chart.setOption(option, true)
    }
  }
}
</script>

<style scoped lang="scss">
.input-long{
  width: 280px;
  ::v-deep .el-input__icon{
    line-height: 22px;
  }
}
</style>
